package com.tencent.common;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.util.security.Credential.MD5;
/*
 * MD5 算法
*/
public class MD5Util {
    
	private final static String[] hexDigits = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
	
	public synchronized static final byte[] toMd5(String data,String encodingType) {
	     MessageDigest digest = null;
	     if (digest == null) { 
	    try { 
	    digest = MessageDigest.getInstance("MD5"); 
	    } catch (NoSuchAlgorithmException nsae) { 
	    System.err.println("Failed to load the MD5 MessageDigest. "); 
	    nsae.printStackTrace(); 
	    } 
	     } 
	     if (StringUtils.isBlank(data)) { 
	     return null; 
	     } 
	     try { 
	//最重要的是这句,需要加上编码类型
	     digest.update(data.getBytes(encodingType)); 
	     } catch (UnsupportedEncodingException e) { 
	     digest.update(data.getBytes()); 
	     } 
	     return digest.digest(); 
	    }
	
	public static String MD5Encode(String origin,String encodingType){
		byte[] md5Bytes = toMd5(origin, encodingType);
		return byteArrayToHexString(md5Bytes);
	}
	
	public static String byteArrayToHexString(byte[] b) {
	        StringBuffer resultSb = new StringBuffer();
	        for (int i = 0; i < b.length; i++) {
	            resultSb.append(byteToHexString(b[i]));
	        }
	        return resultSb.toString();
	    }
	    private static String byteToHexString(byte b) {
	        int n = b;
	        if (n < 0) n = 256 + n;
	        int d1 = n / 16;
	        int d2 = n % 16;
	        return hexDigits[d1] + hexDigits[d2];
	    }

    public static void main(String[] args) {
    	MD5Util getMD5 = new MD5Util();
    	String signTemp = "act_name=绑定顾客奖励&client_ip=127.0.0.1&mch_billno=1307394501201606236672725129&mch_id=1307394501&nonce_str=cae6dbe11e9145dcb44acf57e2a4c49d&re_openid=ojWZZwOGTRn5JatWc2YzEp2VeeFE&remark=绑定顾客越多，红包越多&send_name=盛时&total_amount=100&total_num=1&wishing=恭喜领取红包&wxappid=wx42c6025ff9bb2576&key=6bed007d4e5f4edeb8e70b28d7f47bfa";
 //   	signTemp = "123456yys鷇音子";
		String sign = MD5Util.MD5Encode(signTemp, "utf-8");
    	System.out.println(sign.toUpperCase());
    }
}